package com.ji;

import info.yangguo.perseus.DataSourceHolder;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Title:
 * Description:
 * Author:吉
 * Since:2017/6/27
 * Version:1.1.0
 */
public class JiDataSource extends AbstractRoutingDataSource {
    private AtomicInteger counter = new AtomicInteger();

    public DataSource getMaster() {
        return master;
    }

    public void setMaster(DataSource master) {
        this.master = master;
    }

    public List<DataSource> getSlaves() {
        return slaves;
    }

    public void setSlaves(List<DataSource> slaves) {
        this.slaves = slaves;
    }

    private DataSource master;
    private List<DataSource> slaves;


    @Override
    protected Object determineCurrentLookupKey() {
        return null;
    }
    @Override
    public void afterPropertiesSet() {
        System.out.println("进来了");
    }
    @Override
    protected DataSource determineTargetDataSource() {
        if (DataSourceHolder.isMaster()) {
            System.out.println("用主库");
            return master;
        } else {
            int n = counter.incrementAndGet();
            if (n > 10000) {
                counter.set(0);
            }
            int index = n % slaves.size();
            System.out.println("用从库");
            return slaves.get(index);
        }
    }
}
